package world.player;


import gui.gui2d.eventsmanager.MouseListenerChess;
import gui.gui2d.eventsmanager.MouseListenerSelecterPiece;

import java.util.Observable;
import java.util.Observer;

import core.ChatActionListenerSend;
import multiplayer.lan.utility.Message;
import utility.Color;
import utility.EventPass;
import utility.MyMessage;
import utility.Point;
import world.ChessBoardMenager;
import world.Piece;


public class LocalPlayer extends Player implements Observer{
	Long ms;
	int click=0;
	Point from;
	boolean iPlayng=false;
	public LocalPlayer(Color color) {
		super(color);
		from= new Point(0, 0);
		ms=System.currentTimeMillis() ;
	}

	@Override
	public void move(Point from, Point to) {
		if(gameManager.canMove(this)){
			gameManager.move(this, from, to);
		}else{
			gameManager.youCantMove(this);
			System.out.println("You can't move now");
		}

	}
	@Override
	public void update(Observable o, Object arg) {
		if(o instanceof MouseListenerChess){
			ChessBoardMenager cbm = gameManager.getChess().getChessBoardMenager();
			EventPass ep= (EventPass) arg;
			Piece p= cbm.getMatrix()[ep.getPoint().getX()][ep.getPoint().getY()];
			if(click==0){
				long now=System.currentTimeMillis();
				if(now-ms<600){
					//System.out.println("anti mouse pulse");
					return;
				}else{
					ms=System.currentTimeMillis();;
				}
				if(p==null){
					//System.out.println("No clicked piece");
				}else{
					if(p.getColor().equals(this.color)){
						if(gameManager.canMove(this)){
							gameManager.notifyClick(this,ep.getPoint());
							from=ep.getPoint();
							iPlayng=true;
							click=1;
							return;
						}else{
							gameManager.youCantMove(this);
							return;
						}

					}
				}
			}if(click==1){
				if(iPlayng){
					if(p!= null && p.getColor().equals(this.color)){
						if(gameManager.canMove(this)){
							gameManager.notifyClick(this,ep.getPoint());
							from=ep.getPoint();
							iPlayng=true;
							click=1;
							return;
						}
					}else{
						gameManager.notifyClick(this,null);
						iPlayng=false;
						move(from,ep.getPoint());
						click=0;
					}
				}

			}
		}else if(o instanceof MouseListenerSelecterPiece){
			//System.out.println("local player received");
			Piece piece= (Piece) arg;
			gameManager.makePromotionPown(piece);
			
		}
		else if(o instanceof ChatActionListenerSend){
			String message= (String) arg;
			gameManager.sendMessageFromLocalPlayer(message);
			
		}
	}
}

